package com.example.textviewpartclickable;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = findViewById(R.id.textView);

        // 通过style来设置
        SpannableStringBuilder style = new SpannableStringBuilder();
        style.append("同意《XX协议》");

        // 设置点击
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                // 去掉下划线
                ds.setUnderlineText(false);
            }
            @Override
            public void onClick(@NonNull View widget) {
                Toast.makeText(getApplicationContext(), "点击", Toast.LENGTH_SHORT).show();
            }
        };
        style.setSpan(clickableSpan, 2, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        // 设置高亮颜色为透明，这样点击后这个span的背景就不会变/一直保持某些颜色了
        textView.setHighlightColor(getColor(R.color.transparent));


        // 设置颜色
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#0000FF"));
        style.setSpan(foregroundColorSpan, 2, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(style);
    }
}